//
//  LDY_ReadContectViewController.m
//  ProjectOfBStage
//
//  Created by dlios on 15/11/16.
//  Copyright © 2015年 cuixin. All rights reserved.
//

#import "LDY_ReadContectViewController.h"
#import "Network.h"
#import "LDY_DataBaseManager.h"

@interface LDY_ReadContectViewController ()<UIWebViewDelegate>

@property (nonatomic, retain) NSString *html;

@property (nonatomic, retain) UIWebView *webView;

@property (nonatomic, assign) NSInteger i;

@property (nonatomic, retain) UILabel *commentLabel;

@property (nonatomic, retain) UILabel *likeLabel;

@property (nonatomic, retain) UIButton *changeFontButton;

@property (nonatomic, retain) UIView *changeFontView;

@property (nonatomic, retain) UIButton *changeButton;

@property (nonatomic, assign) NSInteger font;

@property (nonatomic, retain) UIButton *plusButton;

@property (nonatomic, retain) UIButton *minusButton;

@property (nonatomic, retain) UIButton *collectionButton;

@property (nonatomic, retain) LDY_DataBaseManager *dataBase;

@end

@implementation LDY_ReadContectViewController

- (void)dealloc
{
    [_ID release];
    [_html release];
    [_webView release];
    [_commentLabel release];
    [_likeLabel release];
    [_changeFontView release];
    [_dataBase release];
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // 创建数据库
        self.dataBase = [LDY_DataBaseManager shareDataBaseManager];
        // 连接数据库
        [self.dataBase connectDataBase:@"DataBase.sqlite"];
        // 创建表
        [self.dataBase executeSQLString:@"create table if not exists LDYSaveTable(l_id text primary key, l_img text, l_title text, l_content text)"];
        
        //初始化字体大小
        self.font = 100;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.barViewLeftButton setImage:[UIImage imageNamed:@"iconfont-xiangzuojiantou"] forState:UIControlStateNormal];
    [self.barViewLeftButton addTarget:self action:@selector(barViewLeftButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    
    self.barViewRightButton.frame = CGRectMake(KWIDTH * 345, KHEIGHT * 20, KWIDTH * 20, KWIDTH * 20);
    [self.view addSubview:self.barViewRightButton];
    [self.barViewRightButton setImage:[UIImage imageNamed:@"collect"] forState:UIControlStateNormal];
    [self.barViewRightButton addTarget:self action:@selector(barViewRightButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *commentImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pinglun"]];
    [self.barView addSubview:commentImageView];
    commentImageView.frame = CGRectMake(KWIDTH * 220, KHEIGHT * 22, KWIDTH * 16, KWIDTH * 16);
    [commentImageView release];
    
    self.commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(KWIDTH * 223 + commentImageView.frame.size.width, KHEIGHT * 20, KWIDTH * 50, KHEIGHT * 20)];
    self.commentLabel.textColor = [UIColor grayColor];
    self.commentLabel.font = [UIFont systemFontOfSize:10];
    [self.view addSubview:self.commentLabel];
    [self.commentLabel release];
    
    UIImageView *likeImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"blackHeart"]];
    [self.view addSubview:likeImageView];
    likeImageView.frame = CGRectMake(KWIDTH * 275, KHEIGHT * 20, KWIDTH * 19, KWIDTH * 19);
    [likeImageView release];
    
    self.likeLabel = [[UILabel alloc] initWithFrame:CGRectMake(KWIDTH * 278 + likeImageView.frame.size.width, KHEIGHT * 20, KWIDTH * 50, KWIDTH * 20)];
    self.likeLabel.textColor = [UIColor grayColor];
    self.likeLabel.font = [UIFont systemFontOfSize:10];
    [self.view addSubview:self.likeLabel];
    [self.likeLabel release];
    
    self.changeFontButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.barView addSubview:self.changeFontButton];
    self.changeFontButton.frame = CGRectMake(KWIDTH * 150, KHEIGHT * 20, KWIDTH * 19, KWIDTH * 19);
    [self.changeFontButton setImage:[UIImage imageNamed:@"changeFont"] forState:UIControlStateNormal];
    
    [self.changeFontButton addTarget:self action:@selector(pushChangeFontView:) forControlEvents:UIControlEventTouchUpInside];

    self.changeFontView = [[UIView alloc] initWithFrame:CGRectMake(0, 45 * KHEIGHT, KWIDTH * 375, KHEIGHT * 150)];
    [self.view addSubview:self.changeFontView];
    self.changeFontView.backgroundColor = [UIColor clearColor];
    
    UIVisualEffectView *visual = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle: UIBlurEffectStyleDark]];
    visual.frame = CGRectMake(0, 0, KWIDTH * 375, KHEIGHT * 150);
    [self.changeFontView addSubview:visual];
    visual.alpha = 0.7;
    [visual release];
    
    NSArray *titleArr = @[@"A-", @"A+", @"日间", @"夜间"];
    int k = 0;
    
    for (int i = 0; i < 2; i++) {
        for (int j = 0; j < 2; j++) {
            UIButton *changeButton = [UIButton buttonWithType:UIButtonTypeCustom];
            [self.changeFontView addSubview:changeButton];
            changeButton.frame = CGRectMake(KWIDTH * 30 + j * KWIDTH * 170, KHEIGHT * 10 + i * KHEIGHT * 70, KWIDTH * 150, KHEIGHT * 60);
            changeButton.backgroundColor = [UIColor whiteColor];
            changeButton.tag = 1000 + 10 * i + j;
            [changeButton setTitle:titleArr[k] forState:UIControlStateNormal];
            [changeButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            
            [changeButton addTarget:self action:@selector(changeButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
            if (changeButton.tag == 1011) {
                changeButton.backgroundColor = [UIColor blackColor];
                [changeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            }
            
            self.minusButton = (UIButton *)[self.view viewWithTag:1000];
            
            self.plusButton = (UIButton *)[self.view viewWithTag:1001];
            
            k++;
        }
    }
    
    [self dataHandle];
    
    // 获取
    NSArray *array = [self.dataBase execuateQuerySQL:@"select * from LDYSaveTable"];
    NSLog(@"~~~~~~~~~~~~%@",array);
    // 判断数据里有没有存入相同字段的东西
    int count = 0;
    for (int i = 0; i < array.count; i++) {
        if ([self.ID isEqualToString:[array[i] objectForKey:@"l_id"]]) {
            count++;
            NSLog(@"@@@@@@@@@@@@@@@@@@@@@");
        }
    }
    if (count > 0) {
        [self.barViewRightButton setImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
        
    } else if (count == 0) {
        [self.barViewRightButton setImage:[UIImage imageNamed:@"collect"] forState:UIControlStateNormal];
    }
}

/* 返回事件 */
- (void)barViewLeftButtonClicked
{
    self.tabBarController.tabBar.hidden = NO;
    [self.navigationController popViewControllerAnimated:YES];
    self.navigationController.navigationBarHidden = NO;
}


- (void)barViewRightButtonClicked:(UIButton *)button
{
    NSLog(@"barViewRightButtonClicked");
    
    int count = 0;
    // 获取
    NSArray *array = [self.dataBase execuateQuerySQL:@"select * from LDYSaveTable"];
    // 判断数据里有没有存入相同字段的东西
    NSLog(@"++++++++++%@",array);
    
    for (int i = 0; i < array.count; i++) {
        if ([self.ID isEqualToString:[array[i] objectForKey:@"l_id"]]) {
            count++;
        }
    }
    
    if (count > 0) {
        // 删除数据库中的数据
        [self.dataBase execuateQuerySQL:[NSString stringWithFormat:@"delete from LDYSaveTable where l_id = '%@'", self.ID]];
        [self.barViewRightButton setImage:[UIImage imageNamed:@"collect"] forState:UIControlStateNormal];
        UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经取消收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [al show];
        [self.view addSubview:al];
        [al release];
        
    } else {
        // 数据库添加信息
        [self.dataBase executeSQLString:[NSString stringWithFormat:@"insert into LDYSaveTable(l_id, l_img, l_title, l_content) values('%@', '%@', '%@', '%@')", [NSString stringWithFormat:@"%@", self.ID], self.img, self.titleName, self.content]];
        
        [self.barViewRightButton setImage:[UIImage imageNamed:@"collected"] forState:UIControlStateNormal];
        UIAlertView *al = [[UIAlertView alloc] initWithTitle:@"提示" message:@"已经收藏" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [al show];
        [self.view addSubview:al];
        [al release];
    }
}

- (void)pushChangeFontView:(UIButton *)button
{
    [self.view exchangeSubviewAtIndex:5 withSubviewAtIndex:6];
}

- (void)dataHandle
{
    NSString *body = [NSString stringWithFormat:@"auth=&client=1&contentid=%@&deviceid=7F95D47F-BF62-4528-B18E-EE921FFC5323&version=3.0.6", self.ID];
    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 45 * KHEIGHT, KWIDTH * 375, KHEIGHT * 667 - 45 * KHEIGHT)];
    self.webView.delegate = self;
    self.webView.scrollView.bounces = NO;
    
    [self.view addSubview:self.webView];
    
    [Network networkPOSTRequestWithURL:@"http://api2.pianke.me/article/info" body:body pageUniquenessIdentifier:body result:^(id result) {
        
        NSDictionary *mDic = result;
        
        NSDictionary *dic = [mDic objectForKey:@"data"];
        
        NSDictionary *counterDic = [dic objectForKey:@"counterList"];
        
        self.commentLabel.text = [NSString stringWithFormat:@"%@", [counterDic objectForKey:@"comment"]];
        self.likeLabel.text = [NSString stringWithFormat:@"%@", [counterDic objectForKey:@"like"]];
        
        self.html = [dic objectForKey:@"html"];
        
        [self.webView loadHTMLString:self.html baseURL:nil];
        
    }];
}

- (void)changeButtonClicked:(UIButton *)button
{
    NSLog(@"%ld", button.tag);
    
    if (button.tag == 1000) {
        if (self.font >= 100) {
            self.font -= 10;
        }
        NSString *str = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%ld%%'", (long)self.font];
        [self.webView stringByEvaluatingJavaScriptFromString:str];
        
    }else if (button.tag == 1001) {
        
        if (self.font <= 120) {
            self.font += 10;
        }
        NSString *str = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%ld%%'", (long)self.font];
        [self.webView stringByEvaluatingJavaScriptFromString:str];
        
    }else if (button.tag == 1010) {
        
        [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].style.webkitTextFillColor= '#000000'"];
        [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].style.backgroundColor='#ffffff'"];
    }else{
        
        [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].style.webkitTextFillColor= '#e6e6e6'"];
        [self.webView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].style.background='#2c2c2c'"];
    }
    
    if (self.font == 90) {
        self.minusButton.backgroundColor = [UIColor lightGrayColor];
    }else{
        self.minusButton.backgroundColor = [UIColor whiteColor];
    }
    
    if (self.font == 130) {
        self.plusButton.backgroundColor = [UIColor lightGrayColor];
    }else{
        self.plusButton.backgroundColor = [UIColor whiteColor];
    }
}

/* webView自适应 */
- (void)webViewDidFinishLoad:(UIWebView *)webView { //webview 自适应高度
    [webView stringByEvaluatingJavaScriptFromString:
     @"var script = document.createElement('script');"
     "script.type = 'text/javascript';"
     "script.text = \"function ResizeImages() { "
     "var myimg,oldwidth;"
     "var maxwidth= 305;"//缩放系数,调动这个参数可以改变图片的宽度
     "for(i=0;i <document.images.length;i++){"
     "myimg = document.images[i];"
     "oldwidth = myimg.width;"
     "if (oldwidth >= 300) {"
     "myimg.width = maxwidth;"
     "myimg.height = myimg.height;"
     "}"
     "}"
     "}\";"
     "document.getElementsByTagName('head')[0].appendChild(script);"];
    
    [webView stringByEvaluatingJavaScriptFromString:@"ResizeImages();"];
    
    NSString *str = @"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '100%'";
    [webView stringByEvaluatingJavaScriptFromString:str];
    
    self.i++;
    [self hideWaiting];
    self.tabBarController.tabBar.hidden = YES;
}

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if (self.i <= 0) {
        return YES;
    }else
        return NO;
}

//因为能左右滑动,多以消除滚动轮指示器,防止左走乱窜
-(void)hideWaiting
{
    [[self.view viewWithTag:9998] removeFromSuperview];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
